from django.shortcuts import render, HttpResponse, redirect, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required

from page.utils import get_active_diagnostic_test
from engonline.models import UserAnswer, TextArtefact
from account.decorators import staff_required
from keelback.text_identifiers import WELCOME, JOIN_GROUP

@login_required
def home(request):
	"""
	Returns the intro page if the user does not have an answer recorded for 
	the current diagnostic test. Otherwise, returns a redirect to my progress.
	"""
	if request.method == 'POST':
		group = get_object_or_404(Group, id=request.POST['group_id'])
		request.user.groups.add(group)
		request.user.save()

	if request.user.groups.all() or request.user.is_staff:
		try:
			# If a diagnostic test has been performed, re-direct to My Progress
			done_diagnostic = UserAnswer.objects.filter(user=request.user, 
				test=get_active_diagnostic_test()).exists()
			if done_diagnostic:
				return redirect('account.views.my_progress')
		except Exception, e:
			pass

		# Get the welcome text
		try:
			welcome = TextArtefact.objects.get(name=WELCOME)
		except Exception, e:
			welcome = {"html": "Error"}

		return render(request, 'home.html', {'welcome': welcome})
	else:
		# Get the join group text
		try:
			join_group_text = TextArtefact.objects.get(name=JOIN_GROUP)
		except Exception, e:
			join_group_text = {"html": "Error"}
		return render(request, 'join_group.html', {'groups':Group.objects.all(), 'join_group_text': join_group_text})


@login_required
@staff_required
def view_as(request):
	"""
	Sets the viewing_as_student session variable to true or false.
	Returns 404 if not POST and ajax.
	"""
	if request.method == 'POST' and request.is_ajax():
		try:
			view_as = request.POST['view-as']

			if view_as == 'student':
				request.session['viewing_as_student'] = True
			else:
				request.session['viewing_as_student'] = False

			return HttpResponse(status=200)
		except Exception, e:
			return HttpResponse(status=400)
	else:
		raise Http404

@login_required
@staff_required
def list_text_artefacts(request):
	"""
	Lists all TextArtefacts.
	"""
	texts = TextArtefact.objects.all()

	return render(request, 'list_text_artefacts.html', {'texts': texts})

@login_required
@staff_required
def edit_text_artefact(request, text_artefact=None):
	"""
	View (GET) or edit (POST) a TextArtefact.
	"""
	text = get_object_or_404(TextArtefact, name=text_artefact)

	if request.method == 'POST' and request.is_ajax():
		return _edit_text_artefact_POST(request, text)
	else:
		return _edit_text_artefact_GET(request, text)
	

def _edit_text_artefact_GET(request, text):
	return render(request, 'edit_text_artefact.html', {'text': text})

def _edit_text_artefact_POST(request, text):
	try:
		html = request.POST['editor']
		text.html = html
		text.save()
		return HttpResponse(status=200)
	except Exception, e:
		return HttpResponse(status=400)
